// pages/have/service/service.js
const app = getApp()
import { getCityCartypeDealerList, distanceFind, getServiceData } from '../../../api/api.js';
import { tips } from '../../../utils/show.js'
var QQMapWX = require("../../../libs/qqmap-wx-jssdk.min.js")
var demo = new QQMapWX({
  key: app.globalData.serviceKey // 必填
});

Page({
  data: {
    height: app.globalData.height * 2 + 20, 
    nvabarData: {
      showCapsule: 1, //是否显示左上角图标   1表示显示    0表示不显示
      title: '服务站查询 ', //导航栏 中间的标题
      img: "../../image/back.png"
    },
    list: [], // 列表
    lat: 13,  // 当前经度
    lng: 13,  // 当前纬度
    slProv: '',  // 默认选择省份
    slCity: '',
    slCar: '', // 默认选择车型
    showProv: false,
    showCity: false,
    showCar: false,
    allData: {},
    provData: [], // 省份数据
    cityData: [], // 城市数据
    carData: [],  // 车型数据
    markers: [],
    defaultProv: '',
    defaultCity: ''
  },
 
  // 点击下拉显示框
  selectTap(e) {
    const type = parseInt(e.currentTarget.dataset.type);
    // console.log(type);
    if (type === 1) {
      this.setData({
        showProv: !this.data.showProv,
        showCity: false
      });
    } else {
      this.setData({
        showCar: !this.data.showCar
      });
    }
  },
  // 点击下拉列表
  optionTap(e) {
    let value = e.currentTarget.dataset.value; // 获取点击的下拉列表的下标
    const type = parseInt(e.currentTarget.dataset.type);
    if (type === 1) {
      this.setData({
        showProv: !this.data.showProv,
        slProv: value
      });
    } else {
      this.setData({
        showCar: !this.data.showCar,
        slCar: value
      });
    }
    this.getList();//加载下面列表数据
  },

  // 
  showCityTap(e) {
    let value = e.currentTarget.dataset.value; // 获取点击的下拉列表的下标
    const cityData = this.data.allData[value];
    this.setData({
      cityData,
      showCity: true,
      slProv: value
    });
  },

  clickCityTap (e) {
    let value = e.currentTarget.dataset.value;
    this.setData({
      slCity: value,
      showProv: false,
      showCity: false
    })
    this.getList();
  },
  onLoad: function (options) {
    this.init();
  },

  // 获取地址，经度纬度
  // 获取省份，车型
  // 获取数据
  async init () {
    const r = await this.getLocation();
    const adressData = await this.getProv(r.latitude,r.longitude);  // 当前经度纬度
    console.log(adressData);
    const prov = adressData.result.address_component.province;      // 当前省份
    const city = adressData.result.address_component.city;      // 当前市区
    const res = await this.getProvCarData();
    console.log('省份数据');
    console.log(res);
    if (res.code != 0) {
      app.showToast('数据出错');
      return;
    }
    const carType = res.data.carType;
    const provData = [];
    for (let k in res.data.provCity) {
      provData.push(k)
    }
    const cityData = res.data.provCity[prov];
    const allData = res.data.provCity;
    this.setData({
      lat: r.latitude,
      lng: r.longitude,
      slProv: prov,
      slCity: city,
      slCar: carType[0],
      allData,
      provData,
      cityData,
      carData: carType,
      defaultProv: prov,
      defaultCity: city
    });
    this.getList();
  },
  // 获取当前位置的经度和纬度
  getLocation () {
    return new Promise ((resolve, reject) => {
      wx.getLocation({
        success (res) { resolve(res); },
        fail (err) { reject(err); }
      })
    })
  },
  // 根据经度纬度获取当前的省份
  getProv (latitude = this.data.latitude, longitude = this.data.longitude) {
    return new Promise((resolve,reject) => {
      demo.reverseGeocoder({
        location: latitude+','+ longitude,
        success: function(res) { resolve(res); },
        fail: function (res) { reject(res); },
      });
    });
  },
  // 获取所有省份和车型
  getProvCarData() {
    return new Promise((resolve,reject) => {
      getServiceData().then(res => {
        if (res.code == 0) {
          resolve(res)
        } else {
          reject(res)
        }
      })
    })
  },
  getList () {
    let data = {
      prov: this.data.slProv,
      city: this.data.slCity,
      car: this.data.slCar
    };
    app.showLoading();
    getCityCartypeDealerList(data).then(res => {
      const markers = [];
      app.hideLoading();
      if (res.code == 0) {
        for (let i in res.data) {
          markers.push(res.data[i]);
        }
        this.setData({
          markers,
          list: res.data
        })
      } else {
        this.setData({ list: [] });
        tips(res.msg);
      }
    })
  },
  //离我最近
  getnearList:function(){
     var that = this;
     var la = this.data.lat;
     var lg = that.data.lng;
     var prov = that.data.defaultProv;
     var city = that.data.defaultCity;
     var slcar = that.data.slCar;
     var data = {
       longitude:lg,
       latitude:la,
       city:city,
       prov,
       car:slcar
     };
     app.showLoading();
     distanceFind(data).then(res=>{
       app.hideLoading();
       if (res.code === 0) {
         let arr = res.data.sort( (obj1,obj2) => {
           const distance1 = obj1.distance;
           const distance2 = obj2.distance;
           if (distance1 < distance2) {
             return -1;
           } else if (distance1 > distance2) {
             return 1;
           } else {
             return 0;
           }
         })
         arr = arr.filter( v => v.distance < 50 )
         this.setData({
          list: arr,
          markers: arr
         })
       }
     })
  },

  // 打开地图
  openMap (e) {
    let { latitude,longitude,name } = e.currentTarget.dataset;
    // console.log(latitude, longitude, name);
    latitude = parseFloat(latitude);
    longitude = parseFloat(longitude);
    wx.openLocation({
      latitude,
      longitude,
      name,
      scale: 18
    })
  },


  getProvList: function() {
    const self = this
    wx.request({
      url: 'http://fukanghui.180depangzi.com/wxapi.php/service/station',
      method: 'GET',
      dataType: 'json',
      success: function(res){
        // console.log('res',res);
        // console.log(res.data.data.provCity)
        const data = [];
        for(let k in res.data.data.provCity) {
          data.push(k)
        }
        
        self.setData({
          selectProv: data,
          selectCar: res.data.data.carType,
          slcar: res.data.data.carType[0]
        });
        self.getLocList();
     
      }
    })
    
  },

  /** 拨打电话 */
  callMobile: function(e){
    const mobile = e.currentTarget.dataset.mobile;
    wx.makePhoneCall({
      phoneNumber: mobile
    });
  },

})
